<template>
  <div class="search-page">
    <!-- 搜索区域 -->
    <div class="search-container">
      <van-search
        v-model="searchKeyword"
        placeholder="请输入搜索关键词"
        show-action
        @search="handleSearch"
        @cancel="handleCancel"
      >
        <template #action>
          <div @click="handleSearch">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 筛选区域 -->
    <div v-if="searchKeyword" class="filter-container">
      <van-dropdown-menu>
        <van-dropdown-item
          v-model="selectedCategory"
          :options="categoryOptions"
          @change="handleCategoryChange"
        />
        <van-dropdown-item
          v-model="selectedSection"
          :options="sectionOptions"
          @change="handleSectionChange"
        />
      </van-dropdown-menu>
    </div>

    <!-- 热门搜索 -->
    <div class="hot-search" v-if="!searchKeyword">
      <h3 class="section-title">热门搜索</h3>
      <div class="tag-list">
        <van-tag round
          v-for="tag in hotTags"
          :key="tag"
          type="warning"
          size="medium"
          @click="searchTag(tag)"
        >
          {{ tag }}
        </van-tag>
      </div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
      <div class="section-header">
        <h3 class="section-title">搜索历史</h3>
        <van-icon name="delete" @click="clearHistory" />
      </div>
      <div class="history-list">
        <div
          v-for="item in searchHistory"
          :key="item"
          class="history-item"
          @click="searchTag(item)"
        >
          <van-icon name="clock-o" />
          <span>{{ item }}</span>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="searchKeyword">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadMore"
      >
        <div
          v-for="item in searchResults"
          :key="item.newsId || item.id"
          class="search-result-item"
          @click="goToDetail(item.newsId || item.id)"
        >
          <div class="result-content">
            <h3 class="result-title">{{ item.title }}</h3>
            <p class="result-summary">{{
              item.contentPreview ||
              (item.contentText ? item.contentText.substring(0, 100) + '...' : '无内容摘要')
            }}</p>
            <div class="result-meta">
              <span class="category">{{ item.category }}</span>
              <span class="time">{{ formatTime(item.pubTime || item.publishTime) }}</span>
              <span v-if="item.section" class="section">{{ item.section }}</span>
            </div>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 空状态 -->
    <van-empty
      v-if="searchKeyword && searchResults.length === 0 && !loading"
      description="暂无搜索结果"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated, onDeactivated, computed, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, Tag, Icon, List, Cell, Empty, DropdownMenu, DropdownItem, Toast } from 'vant'
import { articleApi } from '../utils/api'
import { formatTime } from '../utils/dateUtils'

// 为组件设置名称，用于keep-alive
defineOptions({
  name: 'SearchPage'
})

const router = useRouter()
const route = useRoute()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedSection = ref('')
const categories = ref([])
const sections = ref([])
const hotTags = ref(['学院', '马克思'])
const searchHistory = ref([])
const searchResults = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 懒加载状态管理
const isFirstLoad = ref(true) // 是否首次加载
const lastSearchParams = ref(null) // 上次搜索参数
const isFromCache = ref(false) // 是否从缓存恢复
const savedScrollPosition = ref(0) // 保存的滚动位置

// 筛选选项
const categoryOptions = computed(() => {
  const options = [{ text: '全部分类', value: '' }]
  categories.value.forEach(category => {
    options.push({ text: category, value: category })
  })
  return options
})

const sectionOptions = computed(() => {
  const options = [{ text: '全部学院', value: '' }]
  sections.value.forEach(section => {
    options.push({ text: section, value: section })
  })
  return options
})

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) return

  // 添加到搜索历史
  addToHistory(searchKeyword.value.trim())

  // 更新URL参数
  updateUrlParams()

  // 执行搜索（强制搜索）
  performSearch(false, true)
}

// 处理取消
const handleCancel = () => {
  searchKeyword.value = ''
  searchResults.value = []
}

// 搜索标签
const searchTag = (tag) => {
  searchKeyword.value = tag
  // 清除筛选条件
  selectedCategory.value = ''
  selectedSection.value = ''
  handleSearch()
}

// 时间格式化函数已移至 @/utils/dateUtils.js

// 检查搜索参数是否发生变化
const hasSearchParamsChanged = () => {
  const currentParams = {
    keyword: searchKeyword.value.trim(),
    category: selectedCategory.value,
    section: selectedSection.value
  }

  if (!lastSearchParams.value) {
    return true
  }

  return JSON.stringify(currentParams) !== JSON.stringify(lastSearchParams.value)
}

// 保存当前搜索参数
const saveSearchParams = () => {
  lastSearchParams.value = {
    keyword: searchKeyword.value.trim(),
    category: selectedCategory.value,
    section: selectedSection.value
  }
}

// 执行搜索
const performSearch = async (isLoadMore = false, forceSearch = false) => {
  // 如果不是强制搜索且参数没有变化，且不是加载更多，则跳过搜索
  if (!forceSearch && !isLoadMore && !hasSearchParamsChanged() && searchResults.value.length > 0) {
    //console.log('搜索参数未变化，跳过重复搜索')
    return
  }

  if (!isLoadMore) {
    loading.value = true
    finished.value = false
    searchResults.value = []
    currentPage.value = 1
  }

  try {
    const params = {
      keyword: searchKeyword.value.trim(),
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 添加筛选条件
    if (selectedCategory.value) {
      params.category = selectedCategory.value
    }

    if (selectedSection.value) {
      params.section = selectedSection.value
    }

    // 保存搜索参数
    if (!isLoadMore) {
      saveSearchParams()
    }

    // 调用多条件搜索API
    const result = await articleApi.searchWithMultipleConditions(params)

    let articles = []

    // 处理返回数据
    if (result && result.code === 200 && result.data) {
      if (Array.isArray(result.data)) {
        articles = result.data
      } else if (result.data.list && Array.isArray(result.data.list)) {
        articles = result.data.list
        // 检查是否还有更多数据
        const { pageNum, pages } = result.data
        finished.value = pageNum >= pages
      }
    } else if (Array.isArray(result)) {
      articles = result
    } else if (result && result.list && Array.isArray(result.list)) {
      articles = result.list
      const { pageNum, pages } = result
      finished.value = pageNum >= pages
    }

    if (isLoadMore) {
      searchResults.value.push(...articles)
    } else {
      searchResults.value = articles
    }

    // 如果返回的数据少于页面大小，说明已经到最后一页
    if (articles.length < pageSize.value) {
      finished.value = true
    }

  } catch (error) {
    console.error('搜索失败:', error)
    Toast.fail('搜索失败，请重试')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (finished.value) return

  currentPage.value++
  await performSearch(true)
}

// 获取分类和学院列表
const fetchFilters = async () => {
  try {
    // 获取分类列表
    const categoriesResult = await articleApi.getAllCategories()
    if (categoriesResult && Array.isArray(categoriesResult)) {
      categories.value = categoriesResult
    } else if (categoriesResult && categoriesResult.data && Array.isArray(categoriesResult.data)) {
      categories.value = categoriesResult.data
    }

    // 获取学院列表
    const sectionsResult = await articleApi.getAllSections()
    if (sectionsResult && Array.isArray(sectionsResult)) {
      sections.value = sectionsResult
    } else if (sectionsResult && sectionsResult.data && Array.isArray(sectionsResult.data)) {
      sections.value = sectionsResult.data
    }
  } catch (error) {
    console.error('获取筛选选项失败:', error)
  }
}

// 更新URL参数
const updateUrlParams = () => {
  const query = {}

  if (searchKeyword.value.trim()) {
    query.keyword = searchKeyword.value.trim()
  }

  if (selectedCategory.value) {
    query.category = selectedCategory.value
  }

  if (selectedSection.value) {
    query.section = selectedSection.value
  }

  // 只有当查询参数发生变化时才更新路由
  const currentQuery = route.query
  const hasChanged = JSON.stringify(query) !== JSON.stringify(currentQuery)

  if (hasChanged) {
    router.replace({
      path: '/search',
      query
    })
  }
}

// 处理分类变化
const handleCategoryChange = () => {
  updateUrlParams()
  performSearch(false, true)
}

// 处理学院变化
const handleSectionChange = () => {
  updateUrlParams()
  performSearch(false, true)
}

// 添加到搜索历史
const addToHistory = (keyword) => {
  const history = [...searchHistory.value]
  const index = history.indexOf(keyword)
  
  if (index > -1) {
    history.splice(index, 1)
  }
  
  history.unshift(keyword)
  searchHistory.value = history.slice(0, 10) // 最多保存10条
  
  // 保存到本地存储
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 清除搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 跳转到详情页
const goToDetail = (newsId) => {
  router.push({ name: 'news-detail', params: { id: newsId } })
}

// 检查URL参数
const checkUrlParams = (shouldSearch = true, fromCache = false) => {
  const { keyword, category, section } = route.query

  if (keyword) {
    searchKeyword.value = keyword
  } else {
    searchKeyword.value = ''
  }

  if (category) {
    selectedCategory.value = category
  } else {
    selectedCategory.value = ''
  }

  if (section) {
    selectedSection.value = section
  } else {
    selectedSection.value = ''
  }

  // 如果有搜索参数且需要执行搜索，自动执行搜索
  if (shouldSearch && (keyword || category || section)) {
    if (keyword) {
      addToHistory(keyword)
    }
    // 如果是从缓存恢复且参数没有变化，则不重新搜索
    if (fromCache && !hasSearchParamsChanged() && searchResults.value.length > 0) {
      console.log('从缓存恢复，参数未变化，保持现有搜索结果')
      return
    }
    performSearch(false, true)
  }
}

// 监听路由变化
watch(() => route.query, () => {
  // 只有在组件激活状态下才响应路由变化
  if (!isFirstLoad.value) {
    checkUrlParams(true, false) // 路由变化时强制检查
  }
}, { deep: true })

// 页面加载时的初始化
onMounted(async () => {
  console.log('搜索页初始化')
  // 获取搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }

  // 获取筛选选项
  await fetchFilters()

  // 检查URL参数并执行搜索
  if (isFirstLoad.value) {
    checkUrlParams(true)
    isFirstLoad.value = false
  }
})

// 组件激活时（从keep-alive缓存中恢复）
onActivated(() => {
  console.log('搜索页激活')
  isFromCache.value = !isFirstLoad.value

  // 如果不是首次加载，检查URL参数但可能不重新搜索
  if (!isFirstLoad.value) {
    checkUrlParams(true, true) // 传入fromCache=true

    // 恢复滚动位置
    nextTick(() => {
      if (savedScrollPosition.value > 0) {
        window.scrollTo(0, savedScrollPosition.value)
        console.log('恢复滚动位置:', savedScrollPosition.value)
      }
    })
  }
})

// 组件失活时（被keep-alive缓存）
onDeactivated(() => {
  console.log('搜索页失活')
  // 保存当前滚动位置
  savedScrollPosition.value = window.scrollY || document.documentElement.scrollTop
  console.log('保存滚动位置:', savedScrollPosition.value)
})
</script>

<style scoped>
.search-page {
  padding-bottom: 60px; /* TabBar高度 */
  min-height: 100vh;
  background-color: #f7f8fa;
}

.search-container {
  background: white;
  padding: 8px 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin: 16px 16px 12px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 16px 12px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 0 16px;
}

.history-list {
  padding: 0 16px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
  border-bottom: 1px solid #ebedf0;
  color: #646566;
}

.filter-container {
  background: white;
  border-bottom: 1px solid #ebedf0;
}

.search-results {
  background: white;
  margin-top: 8px;
}

.search-result-item {
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-result-item:active {
  background-color: #f7f8fa;
}

.search-result-item:last-child {
  border-bottom: none;
}

.result-content {
  width: 100%;
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.4;
  color: #323233;
  margin: 0 0 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-summary {
  font-size: 14px;
  color: #646566;
  line-height: 1.4;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
}

.result-meta .category {
  color: #1989fa;
  background: #e8f3ff;
  padding: 2px 6px;
  border-radius: 10px;
}

.result-meta .time {
  color: #969799;
}

.result-meta .section {
  color: #ff976a;
  background: #fff7f0;
  padding: 2px 6px;
  border-radius: 10px;
}
</style>
